import {
	workforceManagementWorkshopShiftCheckingInCreate, workforceManagementWorkshopShiftCheckingInData,
	workforceManagementWorkshopShiftCheckingInGet, workforceManagementWorkshopShiftCheckingInRefreshData,
	workforceManagementWorkshopShiftCheckingInUpdate, workforceManagementWorkshopShiftCheckingInUpdateAuditState
} from '../../../../../api/personnel/workshopScheduleShiftAttendanceStatistic';
import handlerCache from '../../../../../mixins/handler-cache';
import jkSaveButton from '../../../../jk-components/jk-save-button';
import jkUpdateButton from '../../../../jk-components/jk-update-button';
import remoteSearchEmpInput from '../../../../technology/order/components/remote-search-emp-input';
import { formatDate, getDayDiff } from '../../../../../utils/jk/jk-tool';
import { workforcemanagementScheduleList } from '../../../../../api/schedule/scheduling';
import { systemBusinessDictPage } from '../../../../../api/basicData/businessDict';
import { workforceManagementEmpLeaveRecordDelete } from '../../../../../api/production/productionMonitor';
let _this = null;
export default {
	components: {
		jkSaveButton, jkUpdateButton, remoteSearchEmpInput
	},
	mixins: [handlerCache],
	props: {
		pageType: {
			type: String,
			default: 'add'
		}
	},
	data() {
		return {
			prefix: 'workforcemanagement:workshopShiftCheckingIn',
			scheduleShiftList: [],
			dataId: null,
			apiItem: {
				'save': workforceManagementWorkshopShiftCheckingInCreate,
				'update': workforceManagementWorkshopShiftCheckingInUpdate
			},
			tableLoading: false,
			updateAuditLoading: false,
			auditStateLoading: false,
			saveBtnLoading: false,
			saveAndEnableBtnLoading: false,
			workshopList: [],
			causeList: [],
			showLoading: true,
			saveDialogState: false,
			ruleForm: {
				'auditState': 0,
				'beLateEmpList': [],
				'belongDate': '',
				'leaveEmpList': [],
				'noCardPunchedEmpList': [],
				'remark': '',
				'scheduleShiftId': null,
				'shiftId': 0,
				'shiftName': '',
				'workshopId': 0,
				'workshopName': ''
			},
			rules: {
				belongDate: [{ required: true, trigger: 'change' }],
				workshopId: [{ required: true, trigger: 'change' }],
				scheduleShiftId: [{ required: true, trigger: 'change' }]
			},
			empFormData: {},
			updateBtnLoading: false
		};
	},
	methods: {
		onUpdateBtn() {
			this.updateBtnLoading = true;
			workforceManagementWorkshopShiftCheckingInRefreshData(this.ruleForm).then(res => {
				this.updateBtnLoading = false;
				if (res.data.status === 200) {
					this.ruleForm = res.data.res;
				}
			});
		},
		onSetAskForLeaveBtn(scope) {
			const workshopItem = this.workshopList.find(x => x.id === this.ruleForm.workshopId) || {};
			this.empFormData = {
				workshopId: workshopItem.id,
				workshopCode: workshopItem.code,
				workshopName: workshopItem.name,
				groupId: scope.row.groupId,
				groupCode: scope.row.groupCode,
				groupName: scope.row.groupName,
				empId: scope.row.empId,
				empCode: scope.row.empCode,
				empName: scope.row.empName,
				postId: scope.row.postId,
				postCode: scope.row.postCode,
				postName: scope.row.postName
			};
		},
		onDeleteAskForLeaveBtn(scope) {
			if (!scope.row.id) {
				this.ruleForm.leaveEmpList.splice(scope.rowIndex, 1);
			} else {
				workforceManagementEmpLeaveRecordDelete({ id: scope.row.id }).then(res => {
					if (res.data.status === 200) {
						this.ruleForm.leaveEmpList.splice(scope.rowIndex, 1);
					}
				});
			}
		},
		onDateTimeChange(e, scope) {
			this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'startDateTime', e[0]);
			this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'endDateTime', e[1]);
			this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'leaveDay', getDayDiff(e[0], e[1]));
		},
		onScheduleShiftChange(e) {
			this.$set(this.ruleForm, 'beLateEmpList', []);
			this.$set(this.ruleForm, 'noCardPunchedEmpList', []);
			this.$set(this.ruleForm, 'leaveEmpList', []);
			let item = {};
			if (e) {
				item = this.scheduleShiftList.find(x => x.id === e);
			} else {
				item = {
					id: null,
					shiftId: null,
					shiftName: null,
					scheduleId: null
				};
			}
			this.$set(this.ruleForm, 'scheduleId', item.scheduleId);
			this.$set(this.ruleForm, 'scheduleShiftId', item.id);
			this.$set(this.ruleForm, 'shiftId', item.shiftId);
			this.$set(this.ruleForm, 'shiftName', item.shiftName);
			this.getAttendanceData();
		},
		getAttendanceData() {
			if (this.ruleForm.workshopId && this.ruleForm.belongDate && this.ruleForm.shiftId) {
				return workforceManagementWorkshopShiftCheckingInData({
					workshopId: this.ruleForm.workshopId,
					belongDate: this.ruleForm.belongDate,
					shiftId: this.ruleForm.shiftId
				}).then(res => {
					if (res.data.status === 200) {
						const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
						this.$set(this.ruleForm, 'beLateEmpList', resData.beLateEmpList || []);
						this.$set(this.ruleForm, 'noCardPunchedEmpList', resData.noCardPunchedEmpList || []);
						resData.leaveEmpList = resData.leaveEmpList ? resData.leaveEmpList.map(x => {
							x.dateTimeRange = x.startDateTime && x.endDateTime ? [x.startDateTime, x.endDateTime] : [];
							return x;
						}) : [];
						this.$set(this.ruleForm, 'leaveEmpList', resData.leaveEmpList);
					}
				});
			}
		},
		onWorkshopChange() {
			this.$set(this.ruleForm, 'scheduleShiftId', null);
			this.$set(this.ruleForm, 'shiftName', null);
			this.$set(this.ruleForm, 'shiftId', null);
			this.$set(this.ruleForm, 'beLateEmpList', []);
			this.$set(this.ruleForm, 'noCardPunchedEmpList', []);
			this.$set(this.ruleForm, 'leaveEmpList', []);
		},
		onDateChange() {
			this.$set(this.ruleForm, 'scheduleShiftId', null);
			this.$set(this.ruleForm, 'shiftName', null);
			this.$set(this.ruleForm, 'shiftId', null);
			this.$set(this.ruleForm, 'beLateEmpList', []);
			this.$set(this.ruleForm, 'noCardPunchedEmpList', []);
			this.$set(this.ruleForm, 'leaveEmpList', []);
			this.scheduleShiftList = [];
			this.getDateScheduleShiftOptionRequest();
		},
		getDateScheduleShiftOptionRequest() {
			if (this.ruleForm.workshopId && this.ruleForm.belongDate) {
				return workforcemanagementScheduleList({
					belongDate: [this.ruleForm.belongDate, this.ruleForm.belongDate],
					workshopId: this.ruleForm.workshopId
				}).then(res => {
					if (res.data.status === 200) {
						const resData = res.data.res;
						if (resData && resData.length) {
							this.scheduleShiftList = resData[0].scheduleShiftList;
						}
					}
				});
			}
		},
		onEditBtn() {
			this.$toOtherRouter({
				name: 'editWorkshopScheduleShiftAttendanceStatistic',
				query: {
					id: this.$route.query.id ? Number(this.$route.query.id) : null
				}
			});
		},
		getCauseListRequest() {
			return systemBusinessDictPage({
				categoryCode: 'REMOVE_EMP_CAUSE',
				pageSize: 100,
				pageNo: 1
			}).then(res => {
				if (res.data.status === 200) {
					this.causeList = res.data.res;
				}
			});
		},
		async getDependentData() {
			this.showLoading = true;
			this.workshopList = this.$store.state.user.userWorkshop.workshopList;
			this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
			});
			if (!this.dataId) {
				this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
			}
			await this.getCauseListRequest();
			if (this.dataId) await this.getDetailRequest();
			await this.getDateScheduleShiftOptionRequest();
			this.showLoading = false;
		},
		onAddAskForLeaveBtn() {
			this.ruleForm.leaveEmpList.push({
				'empCode': '',
				'empId': null,
				'empName': '',
				'endDateTime': '',
				'groupCode': '',
				'groupId': null,
				'groupName': '',
				'id': null,
				'leaveDay': 0,
				'leaveTypeCode': '',
				'leaveTypeId': null,
				'leaveTypeName': '',
				'postId': null,
				'postName': '',
				'startDateTime': '',
				'dateTimeRange': [],
				'workshopCode': '',
				'workshopId': null,
				'workshopName': ''
			});
		},
		onSelectEmpChange(e, scope) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'empId', e.id);
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'empCode', e.code);
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'empName', e.name);
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'groupId', e.groupId);
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'groupCode', e.groupCode);
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'groupName', e.groupName);
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'postId', e.postId);
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'postCode', e.postCode);
				this.$set(this.ruleForm.leaveEmpList[scope.rowIndex], 'postName', e.postName);
			}
		},
		getParamData() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
			params.workshopCode = workshopItem.code;
			params.workshopName = workshopItem.name;
			params.beLateEmpList = params.beLateEmpList.map(x => {
				x.beLateName = this.causeList.find(x => x.id === x.beLateId) ? this.causeList.find(x => x.id === x.beLateId).name : '';
				x.leaveEarlyName = this.causeList.find(x => x.id === x.leaveEarlyId) ? this.causeList.find(x => x.id === x.leaveEarlyId).name : '';
				return x;
			});
			params.leaveEmpList = params.leaveEmpList ? params.leaveEmpList.map(x => {
				x.startDateTime = x.dateTimeRange && x.dateTimeRange.length ? x.dateTimeRange[0] : '';
				x.endDateTime = x.dateTimeRange && x.dateTimeRange.length ? x.dateTimeRange[1] : '';
				x.leaveTypeName = this.causeList.find(x => x.id === x.leaveTypeId) ? this.causeList.find(x => x.id === x.leaveTypeId).name : '';
				return x;
			}) : [];
			params.noCardPunchedEmpList = params.noCardPunchedEmpList.map(x => {
				x.leaveEarlyName = this.causeList.find(x => x.id === x.leaveEarlyId) ? this.causeList.find(x => x.id === x.leaveEarlyId).name : '';
				return x;
			});
			return params;
		},
		onConfirmBtn(type) {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					this.saveRequest(type);
				} else {
					this.$tipsBar(this, 'validator');
				}
			});
		},
		saveRequest(type) {
			if (type === 2) {
				this.saveAndEnableBtnLoading = true;
			} else {
				this.saveBtnLoading = true;
			}
			// 新增
			if (!this.dataId) {
				this.ruleForm.id = null;
				this.apiItem.save(this.getParamData()).then(res => {
					this.saveBtnLoading = false;
					this.saveAndEnableBtnLoading = false;
					if (res.data.status === 200) {
						this.dataId = res.data.res;
						if (type === 2) {
							this.enableRequest(this.dataId).then(res => {
								if (res.data.status === 200) {
									this.$tipsBar(this, 'save');
									this.onJump(this.dataId);
								}
							});
						} else {
							this.$tipsBar(this, 'save');
							this.onJump(res.data.res);
						}
					}
				});
				return;
			}
			// 编辑
			this.apiItem.update(this.getParamData()).then(res => {
				this.saveBtnLoading = false;
				this.saveAndEnableBtnLoading = false;
				if (res.data.status === 200) {
					if (type === 2) {
						this.enableRequest(this.dataId).then(res => {
							if (res.data.status === 200) {
								this.$tipsBar(this, 'save');
								this.getDependentData();
							}
						});
					} else {
						this.$tipsBar(this, 'save');
						this.getDependentData();
					}
				}
			});
		},
		onAuditStateChange() {
			this.auditStateLoading = true;
			this.enableRequest(this.dataId).then(res => {
				this.auditStateLoading = false;
				if (res.data.status === 200) {
					this.getDependentData();
				}
			});
		},
		enableRequest(id) {
			return workforceManagementWorkshopShiftCheckingInUpdateAuditState({ id });
		},
		onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		},
		getDetailRequest() {
			return workforceManagementWorkshopShiftCheckingInGet({ id: this.dataId }).then(res => {
				this.showLoading = false;
				if (res.data.status === 200) {
					const resData = JSON.parse(JSON.stringify(res.data.res));
					resData.leaveEmpList = resData.leaveEmpList ? resData.leaveEmpList.map(x => {
						x.dateTimeRange = [x.startDateTime, x.endDateTime];
						return x;
					}) : [];
					this.ruleForm = resData;
				}
			});
		},
		onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toOtherRouter({
				name: 'editWorkshopScheduleShiftAttendanceStatistic',
				query: { id }
			});
		},
		onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'WorkshopScheduleShiftAttendanceStatistic'
			});
		},
		clearCacheMethod() {
			console.log('缓存');
			Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
				this.getDependentData();
			});
		}
	},
	mounted() {
		this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
		_this = this;
	}
};
